﻿using BLL.Enums;
using DevExpress.Data.Filtering;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BLL
{
    public class StockDetailBLL
    {
        /// <summary>
        /// 增加库存
        /// </summary>
        /// <param name="warehouseID"></param>
        /// <param name="productID"></param>
        /// <param name="quantity"></param>
        /// <param name="s"></param>
        /// <returns></returns>
        public string StockPlus(string warehouseID, string productID, decimal quantity, DevExpress.Xpo.Session s) 
        {
            return StockPlusOrLess(StockOperateType.Plus, warehouseID, productID, quantity, s);
        }
        /// <summary>
        /// 减少库存
        /// </summary>
        /// <param name="warehouseID"></param>
        /// <param name="productID"></param>
        /// <param name="quantity"></param>
        /// <param name="s"></param>
        /// <param name="IsAmple"></param>
        /// <returns></returns>
        public string StockLess(string warehouseID, string productID, decimal quantity,DevExpress.Xpo.Session s,bool IsAmple)
        {
            return StockPlusOrLess(StockOperateType.Less, warehouseID, productID, quantity, s, IsAmple);
        }
        string StockPlusOrLess(StockOperateType sot, string warehouseID, string productID, decimal quantity, DevExpress.Xpo.Session s, bool IsAmple=true)
        {
            string msg = string.Empty;
            TS_StockDetail stockDetail = GetStockDetail(warehouseID, productID, s);
            if (sot == StockOperateType.Plus)
            {
                stockDetail.Quantity = stockDetail.Quantity + quantity;
                stockDetail.Save();
            }
            else
            {
                if (IsAmple && stockDetail.Quantity < quantity)
                {
                    msg=string.Format("货品简码:{0}[库存：{1},销售量：{2}]库存不足！\r\n",
                          stockDetail.ProductID.ProductCode, stockDetail.Quantity, quantity);
                    return msg;
                }
                stockDetail.Quantity = stockDetail.Quantity - quantity;
                stockDetail.Save();
            }
            return msg;
        }
        public static TS_StockDetail GetStockDetail(string warehouseID, string productID, DevExpress.Xpo.Session s)
        {
            TS_StockDetail stockDetail = s.FindObject<TS_StockDetail>(CriteriaOperator.Parse("WarehouseID=? And ProductID=?", warehouseID, productID));
            if (stockDetail != null) return stockDetail;
            stockDetail = new TS_StockDetail(s);
            stockDetail.WarehouseID = s.GetObjectByKey<B_Warehouse>(warehouseID);
            stockDetail.ProductID = s.FindObject<P_Product>(CriteriaOperator.Parse("ProductID=?", productID));
            stockDetail.Save();
            return stockDetail;
        }
    }
}

